#include "UsrAI.h"
#include <set>
#include <vector>
#include <queue>
#include <string>
#include <utility>
#include <cmath>
#include <unordered_set>
#include <iostream>
#include <unordered_map>

using namespace std;
tagGame tagUsrGame;
ins UsrIns;
//
//
tagInfo info;
// 建立地图信息
struct mapInfo
{
    bool visible; // 是否可见
    short type;   // 类型 ： 不可见 0 | 海洋 1 | 空闲 2 | 农民 3 | 建筑 4 |
                  // 树 5 | 石头 6 | 瞪羚 7 | 鱼 8 | 金子 9 | 敌方战船 10 |
    int SN;       // 编号
    int height;   // 高度
    int x, y;     // 横纵坐标
};
int isMyCoast[128][128] = {{0}}; // 是否沿岸 1代表靠岸的陆地 2代表靠岸的海洋
int isEnemyCoast[128][128] = {{0}};
mapInfo mapinfo[128][128];
int dir[4][2] = {
    {0, 1}, {1, 0}, {0, -1}, {-1, 0}};
bool myLand[128][128];
bool enemyLand[128][128];
unordered_set<int> at_ship_count;
vector<pair<int, int>> detectPath;
bool isOnEnemyLand = false;
// 建立关于农民工作状态的数组
vector<tagFarmer> idleFarmers;
vector<tagFarmer> fishingFarmers;
vector<tagFarmer> cuttingFarmers;
vector<tagFarmer> stoneFarmers;
vector<tagFarmer> huntingFarmers;
vector<tagFarmer> buildingFarmers;
vector<tagFarmer> sailingFarmers;
vector<tagFarmer> transportFarmers;
vector<tagArmy> at_ships;
// 建立编号SN -> 类型的哈希表
unordered_map<int, tagFarmer> farmerTable;
unordered_map<int, tagBuilding> buildingTable;
unordered_map<int, tagResource> resourceTable;
// 建立一个对于船是否已经探测的数组
bool isShipVisited[128][128] = {{false}};
// 获取表信息
void UsrAI::getObjectTable()
{
    info = getInfo();

    farmerTable.clear();
    buildingTable.clear();
    resourceTable.clear();

    auto farmers = info.farmers;
    auto buildings = info.buildings;
    auto resources = info.resources;

    for (auto farmer : farmers)
    {
        farmerTable[farmer.SN] = farmer;
    }
    for (auto building : buildings)
    {
        buildingTable[building.SN] = building;
    }
    for (auto resource : resources)
    {
        resourceTable[resource.SN] = resource;
    }
}
// 分配固定的农民做同一件事
unordered_map<int, string> farmerRoles;
unordered_map<int, int> farmerCountRole;
unordered_map<int, string> shipRole;
// 获取农民状态
void UsrAI::getFarmerState()
{
    info = getInfo();
    getObjectTable();

    idleFarmers.clear();
    buildingFarmers.clear();
    cuttingFarmers.clear();
    stoneFarmers.clear();
    fishingFarmers.clear();
    huntingFarmers.clear();
    sailingFarmers.clear();
    transportFarmers.clear();
    at_ships.clear();

    auto farmers = info.farmers;
    for (auto farmer : farmers)
    {
        if (buildingTable.find(farmer.WorkObjectSN) != buildingTable.end())
        {
            buildingFarmers.push_back(farmer);
        }
        else if (resourceTable.find(farmer.WorkObjectSN) != resourceTable.end())
        {
            if (resourceTable[farmer.WorkObjectSN].Type == RESOURCE_TREE)
            {
                cuttingFarmers.push_back(farmer);
            }
            else if (resourceTable[farmer.WorkObjectSN].Type == RESOURCE_STONE)
            {
                stoneFarmers.push_back(farmer);
            }
            else if (resourceTable[farmer.WorkObjectSN].Type == RESOURCE_GAZELLE ||
                     resourceTable[farmer.WorkObjectSN].Type == RESOURCE_ELEPHANT)
            {
                huntingFarmers.push_back(farmer);
            }
        }
        else if (farmer.FarmerSort == 1)
        {
            transportFarmers.push_back(farmer);
            shipRole[farmer.SN] = "transport";
        }
        else if (farmer.FarmerSort == 2)
        {
            sailingFarmers.push_back(farmer);
            shipRole[farmer.SN] = "sailing";
        }
        if (farmer.NowState == HUMAN_STATE_IDLE)
        {
            idleFarmers.push_back(farmer);
        }
    }

    auto armies = info.armies;
    for (auto &army : armies)
    {
        if (army.Sort == 7)
        {
            at_ships.push_back(army);
        }
    }
}
// 村民预分配
int countRole(const string &role)
{
    int count = 0;
    for (auto &kv : farmerRoles)
    {
        if (kv.second == role)
            count++;
    }
    return count;
}
// 估计我方大陆在什么位置
pair<int, int> UsrAI::countAvgLoc()
{
    info = getInfo();
    int avg_x = 0, avg_y = 0;
    int count = 0;
    int sum_x = 0, sum_y = 0;

    for (int i = 0; i < 128; i++)
    {
        for (int j = 0; j < 128; j++)
        {
            if ((*info.theMap)[i][j].height >= 0)
            {
                sum_x += i;
                sum_y += j;
                count++;
            }
        }
    }
    avg_x = sum_x / count;
    avg_y = sum_y / count;
    return {avg_x, avg_y};
}
// 推测敌方大陆位置
pair<int, int> UsrAI::guessEnemyLoc()
{
    auto point = countAvgLoc();
    int x = point.first, y = point.second;
    int enemy_x = 128 - x, enemy_y = 128 - y;
    return {enemy_x, enemy_y};
}
// 获取地图信息
void UsrAI::getMapInfo()
{
    info = getInfo();
    int gameframe = info.GameFrame;
    bool isBusy[128][128] = {{false}};

    auto farmers = info.farmers;
    auto buildings = info.buildings;
    auto resources = info.resources;
    auto enemy_armys = info.enemy_armies;

    // 建议自行创建一张全局的资源图，记录每一格上的对象
    for (int i = 0; i < 128; i++)
    {
        for (int j = 0; j < 128; j++)
        {
            auto curMap = (*info.theMap)[i][j];
            if (stage >= 2)
            {
                if (curMap.type != 0 && mapinfo[i][j].type == 0)
                {
                    mapinfo[i][j] = {
                        true, 11, 0, curMap.height, i, j};
                    isBusy[i][j] = true;
                }
            }
            if (curMap.type == 0)
            {
                mapinfo[i][j] = {
                    false, 0, 0, curMap.height, i, j};
                isBusy[i][j] = true;
            }

            if (curMap.type == 1)
            {
                for (auto &farmer : farmers)
                {
                    if (i == farmer.BlockDR && j == farmer.BlockUR)
                    {
                        mapinfo[i][j] = {
                            true, 3, farmer.SN, curMap.height, i, j};
                        isBusy[i][j] = true;
                    }
                }
                for (auto &building : buildings)
                {
                    if (i == building.BlockDR && j == building.BlockUR)
                    {
                        if (building.Type == BUILDING_HOME || building.Type == BUILDING_ARROWTOWER)
                        {
                            for (int rol = 0; rol < 2; rol++)
                            {
                                for (int col = 0; col < 2; col++)
                                {
                                    mapinfo[i + rol][j + col] = {
                                        true, 4, building.SN, curMap.height, i + rol, j + col};
                                    isBusy[i + rol][j + col] = true;
                                }
                            }
                        }
                        else if (building.Type == BUILDING_CENTER)
                        {
                            for (int rol = -1; rol < 4; rol++)
                            {
                                for (int col = -1; col < 4; col++)
                                {
                                    mapinfo[i + rol][j + col] = {
                                        true, 4, building.SN, curMap.height, i + rol, j + col};
                                    isBusy[i + rol][j + col] = true;
                                }
                            }
                        }
                        else
                        {
                            for (int rol = 0; rol < 3; rol++)
                            {
                                for (int col = 0; col < 3; col++)
                                {
                                    mapinfo[i + rol][j + col] = {
                                        true, 4, building.SN, curMap.height, i + rol, j + col};
                                    isBusy[i + rol][j + col] = true;
                                }
                            }
                        }
                    }
                }
                for (auto &resource : resources)
                {
                    if (i == resource.BlockDR && j == resource.BlockUR)
                    {
                        if (resource.Type == RESOURCE_TREE)
                        {
                            mapinfo[i][j] = {
                                true, 5, resource.SN, curMap.height, i, j};
                            isBusy[i][j] = true;
                        }
                        else if (resource.Type == RESOURCE_STONE)
                        {
                            mapinfo[i][j] = {
                                true, 6, resource.SN, curMap.height, i, j};
                            isBusy[i][j] = true;
                        }
                        else if (resource.Type == RESOURCE_GAZELLE)
                        {
                            mapinfo[i][j] = {
                                true, 7, resource.SN, curMap.height, i, j};
                            isBusy[i][j] = true;
                        }
                        else if (resource.Type == RESOURCE_GOLD)
                        {
                            mapinfo[i][j] = {
                                true, 9, resource.SN, curMap.height, i, j};
                            isBusy[i][j] = true;
                        }
                    }
                }
                for (auto &enemy_army : enemy_armys)
                {
                    mapinfo[i][j] = {
                        true, 10, enemy_army.SN, curMap.height, i, j};
                }
            }

            if (curMap.type == 3)
            {
                mapinfo[i][j] = {
                    true, 1, 0, curMap.height, i, j // 海洋
                };
                isBusy[i][j] = true;
                for (auto resource : resources)
                {
                    if (i == resource.BlockDR && j == resource.BlockUR)
                    {
                        if (resource.Type == RESOURCE_FISH)
                        {
                            mapinfo[i][j] = {
                                true, 8, resource.SN, curMap.height, i, j};
                            isBusy[i][j] = true;
                        }
                    }
                }
                for (auto building : buildings)
                {
                    if (i == building.BlockDR && j == building.BlockUR)
                    {
                        if (building.Type == BUILDING_DOCK)
                        {
                            for (int rol = 0; rol < 2; rol++)
                            {
                                for (int col = 0; col < 2; col++)
                                {
                                    mapinfo[i + rol][j + col] = {
                                        true, 4, building.SN, curMap.height, i + rol, j + col};
                                    isBusy[i + rol][j + col] = true;
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    for (int i = 0; i < 128; i++)
    {
        for (int j = 0; j < 128; j++)
        {
            if (!isBusy[i][j])
            {
                mapinfo[i][j] = {
                    true, 2, 0, (*info.theMap)[i][j].height, i, j};
            }
        }
    }
}
void UsrAI::getShipVisit()
{
    info = getInfo();
    for (auto &farmer : info.farmers)
    {
        if (farmer.FarmerSort == 1 || farmer.FarmerSort == 2)
        {
            isShipVisited[farmer.BlockDR][farmer.BlockUR] = true;
        }
    }
    for (auto &army : info.armies)
    {
        if (army.Sort == AT_SHIP)
        {
            isShipVisited[army.BlockDR][army.BlockUR] = true;
        }
    }
}
void UsrAI::getMyCoast()
{
    info = getInfo();
    for (int i = 0; i < 128; i++)
    {
        for (int j = 0; j < 128; j++)
        {
            if ((*info.theMap)[i][j].height >= 0)
            {
                for (int d = 0; d < 4; d++)
                {
                    int ni = i + dir[d][0], nj = j + dir[d][1];
                    if (ni >= 0 && ni < 128 && nj >= 0 && nj < 128)
                    {
                        if ((*info.theMap)[ni][nj].height < 0)
                        {
                            isMyCoast[i][j] = 1;
                            isMyCoast[ni][nj] = 2;
                        }
                    }
                }
            }
        }
    }
}
void UsrAI::getEnemyCoast()
{
    info = getInfo();
    for (int i = 0; i < 128; i++)
    {
        for (int j = 0; j < 128; j++)
        {
            if (isMyCoast[i][j] == 0 && (*info.theMap)[i][j].height >= 0)
            {
                for (int d = 0; d < 4; d++)
                {
                    int ni = i + dir[d][0], nj = j + dir[d][1];
                    if (ni >= 0 && ni < 128 && nj >= 0 && nj < 128)
                    {
                        if ((*info.theMap)[ni][nj].height < 0)
                        {
                            isEnemyCoast[i][j] = 1;
                            isEnemyCoast[ni][nj] = 2;
                        }
                    }
                }
            }
        }
    }
}
void UsrAI::updateShipStatus(){
    for (auto& ship : info.armies) {
        if (ship.Sort == AT_SHIP) {
            int sn = ship.SN;
            if (seenShipSNs.find(sn) == seenShipSNs.end()) {
                // 新发现的军舰
                seenShipSNs.insert(sn);
                checkShipNum++;
                DebugText("新军舰 SN = " + std::to_string(sn) + "，当前总数：" + std::to_string(checkShipNum));
            }
        }
    }
}
// 获取阶段
int UsrAI::stage = 1;
void UsrAI::checkStage()
{
    info = getInfo();

    if (info.civilizationStage == CIVILIZATION_TOOLAGE && info.farmers.size() >= 14 &&
        info.armies.size() >= 2 && stage == 1)
    {
        DebugText("游戏进入第二阶段");
        stage = 2;
    }
    if (0)
    {
        stage = 3;
    }
    if (0)
    {
        stage = 4;
    }
}
void UsrAI::findFish()
{
    info = getInfo();

    tagResource *fish = nullptr;
    for (auto &resource : info.resources)
    {
        if (resource.Type == RESOURCE_FISH)
        {
            fish = &resource;
            //            DebugText("找到渔场");
            break;
        }
    }
}
void UsrAI::checkMyLand()
{
    info = getInfo();
    for (int i = 0; i < 128; i++)
    {
        for (int j = 0; j < 128; j++)
        {
            if ((*info.theMap)[i][j].height >= 0)
            {
                myLand[i][j] = true;
            }
        }
    }
}
void UsrAI::checkEnemyLand()
{
    info = getInfo();
    for (int i = 0; i < 128; i++)
    {
        for (int j = 0; j < 128; j++)
        {
            if (myLand[i][j] == false && (*info.theMap)[i][j].height >= 0)
            {
                enemyLand[i][j] = true;
            }
        }
    }
}
// 自动攻击敌人
void UsrAI::autoAttackEnemy()
{
    info = getInfo();
    // 找到一个敌军
    tagArmy *enemy_army = nullptr;
    for (tagArmy &army : info.enemy_armies)
    {
        // 优先攻击非建筑单位
        if (army.Sort != 0) // 假设0是建筑或非攻击单位
        {
            enemy_army = &army;
            DebugText("发现敌方单位，准备自动攻击");
            break;
        }
    }

    if (enemy_army != nullptr)
    {
        for (tagArmy &army : info.armies)
        {
            // 所有空闲的战斗单位都参与攻击
            if (army.NowState == HUMAN_STATE_IDLE && (army.Sort == AT_SHIP || army.Sort == AT_CLUBMAN || army.Sort == AT_SLINGER || army.Sort == AT_SWORDSMAN || army.Sort == AT_BOWMAN || army.Sort == AT_SCOUT))
            {
                HumanAction(army.SN, enemy_army->SN);
            }
        }
    }
}
// 获取调试数据
void UsrAI::getDebugTexts()
{
    info = getInfo();
    getFarmerState();

    auto gameframe = info.GameFrame;
    auto farmers = info.farmers;

    if (gameframe % 100 == 0)
    {
        DebugText("当前游戏为第" + std::to_string(gameframe) + "帧");

        for (int i = 0; i < 128; i++)
        {
            for (int j = 0; j < 128; j++)
            {

                //                if(enemyLand[i][j]){
                //                    DebugText("敌方大陆坐标为 ： " + std::to_string(i) + " " + std::to_string(j));
                //                }

                //                if(isMyCoast[i][j] == 1){
                //                    DebugText("我方海岸坐标为 ： " + std::to_string(i) + " " + std::to_string(j));
                //                }
                //                if(isMyCoast[i][j] == 2){
                //                    DebugText("我方海岸坐标为 ： " + std::to_string(i) + " " + std::to_string(j));
                //                }

//                if (isEnemyCoast[i][j] == 1)
//                {
//                    DebugText("敌方海岸坐标为 ： " + std::to_string(i) + " " + std::to_string(j));
//                }
//                if (isEnemyCoast[i][j] == 2)
//                {
//                    DebugText("敌方海岸坐标为 ： " + std::to_string(i) + " " + std::to_string(j));
//                }

                if (mapinfo[i][j].visible)
                {
                    if (mapinfo[i][j].type == 2)
                    {
                        //                        DebugText("空闲坐标为 ： " + std::to_string(mapinfo[i][j].x) + " " + std::to_string(mapinfo[i][j].y) + "编号为 ： " + std::to_string(mapinfo[i][j].SN));
                    }
                    else if (mapinfo[i][j].type == 3)
                    {
                        //                        DebugText("农民坐标为 ： " + std::to_string(mapinfo[i][j].x) + " " + std::to_string(mapinfo[i][j].y) + "编号为 ： " + std::to_string(mapinfo[i][j].SN));
                    }
                    else if (mapinfo[i][j].type == 4)
                    {
                        //                        DebugText("建筑坐标为 ： " + std::to_string(mapinfo[i][j].x) + " " + std::to_string(mapinfo[i][j].y) + "编号为 ： " + std::to_string(mapinfo[i][j].SN));
                    }
                    else if (mapinfo[i][j].type == 5)
                    {
                        //                        DebugText("树坐标为 ： " + std::to_string(mapinfo[i][j].x) + " " + std::to_string(mapinfo[i][j].y) + "编号为 ： " + std::to_string(mapinfo[i][j].SN));
                    }
                    else if (mapinfo[i][j].type == 1)
                    {
                        //                        DebugText("海洋坐标为 ： " + std::to_string(mapinfo[i][j].x) + " " + std::to_string(mapinfo[i][j].y) + "编号为 ： " + std::to_string(mapinfo[i][j].SN));
                        //                        DebugText("海洋高度为 ： " + std::to_string(mapinfo[i][j].height));
                    }
                    else if (mapinfo[i][j].type == 6)
                    {
                        //                        DebugText("石头坐标为 ： " + std::to_string(mapinfo[i][j].x) + " " + std::to_string(mapinfo[i][j].y) + "编号为 ： " + std::to_string(mapinfo[i][j].SN));
                    }
                    else if (mapinfo[i][j].type == 7)
                    {
                        //                        DebugText("瞪羚坐标为 ： " + std::to_string(mapinfo[i][j].x) + " " + std::to_string(mapinfo[i][j].y) + "编号为 ： " + std::to_string(mapinfo[i][j].SN));
                    }
                    else if (mapinfo[i][j].type == 8)
                    {
                        DebugText("鱼坐标为 ： " + std::to_string(mapinfo[i][j].x) + " " + std::to_string(mapinfo[i][j].y) + "编号为 ： " + std::to_string(mapinfo[i][j].SN));
                    }
                    else if (mapinfo[i][j].type == 9)
                    {
                        //                        DebugText("金子坐标为 ： " + std::to_string(mapinfo[i][j].x) + " " + std::to_string(mapinfo[i][j].y) + "编号为 ： " + std::to_string(mapinfo[i][j].SN));
                    }
                    else if (mapinfo[i][j].type == 11)
                    {
                        //                        DebugText("敌方大陆坐标为 ： " + std::to_string(mapinfo[i][j].x) + " " + std::to_string(mapinfo[i][j].y));
                    }
                }
            }
        }

        //        for(int i = 0; i < 128; i ++){
        //            for(int j = 0; j < 128; j ++){
        //                if(mapinfo[i][j].type == 11){
        //                    DebugText("敌方大陆坐标为 ： " + std::to_string(i) + " " + std::to_string(j));
        //                }
        //            }
        //        }

        //                if(isMyCoast[i][j] == 1){
        //                    DebugText("我方靠海大陆坐标为 ： " + std::to_string(i) + " " + std::to_string(j));
        //                }else if(isMyCoast[i][j] == 2){
        //                    DebugText("我方靠大陆海坐标为 ： " + std::to_string(i) + " " + std::to_string(j));
        //                }else if(isMyCoast[i][j] == 3){
        //                    DebugText("敌方靠海大陆坐标为 ： " + std::to_string(i) + " " + std::to_string(j));
        //                }else if(isMyCoast[i][j] == 4){
        //                    DebugText("敌方靠大陆海坐标为 ： " + std::to_string(i) + " " + std::to_string(j));
        //                }

        DebugText("战舰数量为 ： " + std::to_string(at_ship_count.size()));
        DebugText("上岸情况 ： " + std::to_string(isOnEnemyLand));

        //        DebugText(std::to_string(idleFarmers.size()) + " " + std::to_string(buildingFarmers.size()) + " " +
        //                  std::to_string(cuttingFarmers.size()));

        //        DebugText("建筑数量为 ： " + std::to_string(info.buildings.size()));

        //        for(auto& farmer : idleFarmers){
        //            DebugText("空闲农民为 ： " + std::to_string(farmer.SN));
        //        }
        //        for(auto& farmer : buildingFarmers){
        //            DebugText("建筑农民为 ： " + std::to_string(farmer.SN));
        //        }
        //        for(auto& farmer : cuttingFarmers){
        //            DebugText("砍树农民为 ： " + std::to_string(farmer.SN));
        //        }
        //        for(auto& farmer : huntingFarmers){
        //            DebugText("打猎村民为 ： " + std::to_string(farmer.SN));
        //        }
        //        for(auto& farmer : sailingFarmers){
        //            DebugText("渔船村民为 ： " + std::to_string(farmer.SN));
        //        }

        //        for(auto it = farmerTable.begin(); it != farmerTable.end(); it ++){
        //            DebugText("农民编号为 ： " + std::to_string(it -> first));
        //        }
        //        for(auto it = buildingTable.begin(); it != buildingTable.end(); it ++){
        //            DebugText("建筑编号为 ： " + std::to_string(it -> first));
        //        }
        //        for(auto it = resourceTable.begin(); it != resourceTable.end(); it ++){
        //            DebugText("资源编号为 ： " + std::to_string(it -> first));
        //        }

        DebugText("农民数量为： " + std::to_string(farmers.size()));
//        DebugText("战船数量为： " + std::to_string(info.armies.size()));
        DebugText("当前阶段为： " + std::to_string(stage));

        for(int i = 0; i < detectPath.size(); i ++){
            int x = detectPath[i].first, y = detectPath[i].second;
            DebugText("探测路线为 ： " + std::to_string(x) + " " + std::to_string(y));
        }
    }
}
pair<pair<int, int>, int> UsrAI::bfsSearch(tagObj &origin, int type)
{
    int origin_x = origin.BlockDR, origin_y = origin.BlockUR;

    queue<pair<int, int>> q;
    bool visited[128][128] = {{false}};

    q.push({origin_x, origin_y});
    visited[origin_x][origin_y] = true;

    while (q.size())
    {
        auto p = q.front();
        q.pop();

        if (mapinfo[p.first][p.second].type == type)
        {
            return {{p.first, p.second}, mapinfo[p.first][p.second].SN};
        }

        for (int i = 0; i < 4; i++)
        {
            int dx = p.first + dir[i][0], dy = p.second + dir[i][1];
            if (dx < 0 || dx >= 128 || dy < 0 || dy >= 128 ||
                visited[dx][dy])
            {
                continue;
            }
            if (!visited[dx][dy])
            {
                visited[dx][dy] = true;
                q.push({dx, dy});
            }
        }
    }
    return {};
}
pair<pair<int, int>, int> UsrAI::bfsDockSearch(tagObj &origin)
{
    int origin_x = origin.BlockDR, origin_y = origin.BlockUR;

    queue<pair<int, int>> q;
    bool visited[128][128] = {{false}};

    q.push({origin_x, origin_y});
    visited[origin_x][origin_y] = true;

    while (q.size())
    {
        auto p = q.front();
        q.pop();

        if (mapinfo[p.first][p.second].type == 1 &&
            mapinfo[p.first + 1][p.second].type == 1 && mapinfo[p.first][p.second + 1].type == 1 &&
            mapinfo[p.first + 1][p.second + 1].type == 1)
        {
            return {{p.first, p.second}, mapinfo[p.first][p.second].SN};
        }

        for (int i = 0; i < 4; i++)
        {
            int dx = p.first + dir[i][0], dy = p.second + dir[i][1];
            if (dx < 0 || dx >= 128 || dy < 0 || dy >= 128 ||
                visited[dx][dy])
            {
                continue;
            }
            if (!visited[dx][dy])
            {
                visited[dx][dy] = true;
                q.push({dx, dy});
            }
        }
    }
    return {};
}
// 使用bfs搜索起始位置最近的，并且有地方创建建筑的位置
pair<int, int> UsrAI::bfsSearchBuilding(tagObj &origin, int size, int num)
{
    int origin_x = origin.BlockDR, origin_y = origin.BlockUR;

    queue<pair<int, int>> q;
    bool visited[128][128] = {{false}};

    q.push({origin_x, origin_y});
    visited[origin_x][origin_y] = true;

    while (q.size())
    {
        auto p = q.front();
        q.pop();

        int x = p.first, y = p.second;

        if (x + size <= 128 && y + size <= 128)
        {
            int height = mapinfo[x][y].height;
            bool checkBuild = true;

            for (int i = 0; i < size * num; i++)
            {
                for (int j = 0; j < size; j++)
                {
                    int dx = x + i, dy = y + j;
                    if (mapinfo[dx][dy].type != 2 || mapinfo[dx][dy].height != height)
                    {
                        checkBuild = false;
                        break;
                    }
                }
                if (!checkBuild)
                {
                    break;
                }
            }
            if (checkBuild)
            {
                return {x, y};
            }
        }

        for (int i = 0; i < 4; i++)
        {
            int dx = x + dir[i][0], dy = y + dir[i][1];
            if (dx < 0 || dx >= 128 || dy < 0 || dy >= 128 ||
                visited[dx][dy])
            {
                continue;
            }
            if (!visited[dx][dy])
            {
                visited[dx][dy] = true;
                q.push({dx, dy});
            }
        }
    }
    return {-1, -1};
}
// 使用bfs，获得船只的路径
vector<pair<int, int>> UsrAI::sailingBfsSearch(tagObj &origin, int targetType)
{
    int origin_x = origin.BlockDR, origin_y = origin.BlockUR;

    queue<vector<pair<int, int>>> q; // 存路径
    bool visited[128][128] = {{false}};
    vector<pair<int, int>> invisible_path; // 如果找不到目标，探索不可见海域

    q.push({{origin_x, origin_y}});
    visited[origin_x][origin_y] = true;

    while (!q.empty())
    {
        auto path = q.front();
        q.pop();
        int x = path.back().first;
        int y = path.back().second;

        // 如果找到鱼
        if (mapinfo[x][y].visible && mapinfo[x][y].type == targetType)
        {
            return path;
        }

        // 如果是可走但尚未探索的海域，作为备用路径
        if (!mapinfo[x][y].visible && !isShipVisited[x][y] && invisible_path.empty())
        {
            invisible_path = path;
        }

        for (int i = 0; i < 4; i++)
        {
            int dx = x + dir[i][0];
            int dy = y + dir[i][1];
            if (dx < 0 || dx >= 128 || dy < 0 || dy >= 128)
                continue;
            if (visited[dx][dy])
                continue;

            visited[dx][dy] = true;
            auto new_path = path;
            new_path.push_back({dx, dy});
            q.push(new_path);
        }
    }

    // 返回探索未知区域的路径
    return invisible_path;
}
vector<pair<int, int>> UsrAI::shipBfsSearch(tagObj &origin, int targetType)
{
    int origin_x = origin.BlockDR, origin_y = origin.BlockUR;

    queue<vector<pair<int, int>>> q; // 存路径
    bool visited[128][128] = {{false}};

    q.push({{origin_x, origin_y}});
    visited[origin_x][origin_y] = true;

    while (!q.empty())
    {
        auto path = q.front();
        q.pop();
        int x = path.back().first;
        int y = path.back().second;

        // 找到敌舰
        if (mapinfo[x][y].visible && mapinfo[x][y].type == targetType)
        {
            return path;
        }

        for (int i = 0; i < 4; i++)
        {
            int dx = x + dir[i][0];
            int dy = y + dir[i][1];
            if (dx < 0 || dx >= 128 || dy < 0 || dy >= 128)
                continue;
            if (visited[dx][dy])
                continue;

            if ((mapinfo[dx][dy].visible && mapinfo[dx][dy].type == 1) || !mapinfo[dx][dy].visible)
            {
                visited[dx][dy] = true;
                auto new_path = path;
                new_path.push_back({dx, dy});
                q.push(new_path);
            }
        }
    }

    // 没找到敌舰，调用 bfsSearch 寻找最近的未知海域
    auto unknown_target = bfsSearch(origin, 0); // 0 表示不可见格子
    if (unknown_target.first.first != 0 || unknown_target.first.second != 0)
    {
        // 再次执行 BFS，从 origin 走到 unknown_target
        pair<int, int> target = unknown_target.first;
        queue<vector<pair<int, int>>> q2;
        bool visited2[128][128] = {{false}};
        q2.push({{origin_x, origin_y}});
        visited2[origin_x][origin_y] = true;

        while (!q2.empty())
        {
            auto path = q2.front();
            q2.pop();
            int x = path.back().first;
            int y = path.back().second;

            if (x == target.first && y == target.second)
            {
                return path;
            }

            for (int i = 0; i < 4; i++)
            {
                int dx = x + dir[i][0];
                int dy = y + dir[i][1];
                if (dx < 0 || dx >= 128 || dy < 0 || dy >= 128)
                    continue;
                if (visited2[dx][dy])
                    continue;
                if ((mapinfo[dx][dy].visible && mapinfo[dx][dy].type == 1) || !mapinfo[dx][dy].visible)
                {
                    visited2[dx][dy] = true;
                    auto new_path = path;
                    new_path.push_back({dx, dy});
                    q2.push(new_path);
                }
            }
        }
    }
    return {}; // 完全找不到任何路径
}
vector<pair<int, int>> UsrAI::bfsSearchEnemyLand(tagObj &origin, pair<int, int> &dest)
{
    int origin_x = origin.BlockDR, origin_y = origin.BlockUR;

    queue<vector<pair<int, int>>> q;
    bool visited[128][128] = {{false}};

    q.push({{origin_x, origin_y}});
    visited[origin_x][origin_y] = true;

    while (!q.empty())
    {
        auto path = q.front();
        q.pop();
        int x = path.back().first;
        int y = path.back().second;

        // 如果到了敌方海岸
        if (isEnemyCoast[x][y] == 1 || (abs(x - dest.first) + abs(y - dest.second) <= 1 &&
             ((mapinfo[x][y].visible && mapinfo[x][y].type == 1) || !mapinfo[x][y].visible)))
        {
            dest = {x, y}; // 存储目标坐标
            return path;
        }

        for (int i = 0; i < 4; i++)
        {
            int dx = x + dir[i][0], dy = y + dir[i][1];
            if (dx < 0 || dx >= 128 || dy < 0 || dy >= 128)
                continue;
            if (visited[dx][dy])
                continue;

            // 只在海洋或不可见上前进
            if (!mapinfo[dx][dy].visible || (mapinfo[dx][dy].visible && mapinfo[dx][dy].type == 1))
            {
                visited[dx][dy] = true;
                auto new_path = path;
                new_path.push_back({dx, dy});
                q.push(new_path);
            }
        }
    }

    return {}; // 没找到就返回空路径
}
pair<int, int> UsrAI::bfsSearchMyCoast(tagObj& origin){
//    int origin_x = origin.BlockDR, origin_y = origin.BlockUR;
    info = getInfo();
    for(auto& building : info.buildings){
        if(building.Type == BUILDING_DOCK){
            int x = building.BlockDR, y = building.BlockUR;
            for(int i = 0; i < 3; i ++){
                for(int j = 0; j < 3; j ++){
                    int dx = x + i, dy = y + j;
                    if(isMyCoast[dx][dy] == 2 && mapinfo[dx][dy].type != 4 && mapinfo[dx][dy].type != 8){
                        return {dx, dy};
                    }
                }
            }
        }
    }
    return {-1, -1}; // 如果没找到合适的码头或海岸，返回无效坐标
}
pair<int, int> UsrAI::bfsSearchEnemyCoast(tagObj& origin){
    int origin_x = origin.BlockDR, origin_y = origin.BlockUR;
    queue<pair<int, int>> q;
    bool visited[128][128] = {{false}};

    q.push({origin_x, origin_y});
    visited[origin_x][origin_y] = true;

    while(!q.empty()){
        auto t = q.front();
        q.pop();

        if(isEnemyCoast[t.first][t.second] == 2 && mapinfo[t.first][t.second].type != 4 && mapinfo[t.first][t.second].type != 8){
            return {t.first, t.second};
        }

        for(int i = 0; i < 4; i ++){
            int dx = t.first + dir[i][0], dy = t.second + dir[i][1];

            if(dx < 0 || dx >= 128 || dy < 0 || dy >= 128 || visited[dx][dy]){
                continue;
            }

            visited[dx][dy] = true;
            q.push({dx, dy});
        }
    }
    return {};
}
// 建立建筑类型到大小的关系
int UsrAI::getBuildingSize(int buildingType)
{
    if (buildingType == 0 || buildingType == 6 ||
        buildingType == 10)
    {
        return 2;
    }
    return 3;
}

// 第一阶段农民角色分配
void UsrAI::assignFarmerRoles01()
{
    for (auto &farmer : idleFarmers)
    {
        if (farmerRoles.find(farmer.SN) == farmerRoles.end())
        {
            if (countRole("woodcutter") < 2)
            {
                farmerRoles[farmer.SN] = "woodcutter";
            }
            else if (countRole("builder") < 1)
            {
                farmerRoles[farmer.SN] = "builder";
            }
            else if (countRole("woodcutter") < 5)
            {
                farmerRoles[farmer.SN] = "woodcutter";
            }
            else if (countRole("hunter") < 2)
            {
                farmerRoles[farmer.SN] = "hunter";
            }
            else
            {
                farmerRoles[farmer.SN] = "woodcutter";
            }
        }
    }
}
// 第一阶段农民行为
void UsrAI::farmerDoWork01()
{
    auto buildings = info.buildings;
    for (auto &farmer : idleFarmers)
    {
        string role = farmerRoles[farmer.SN];
        if (role == "builder")
        {
            if (buildings.size() < 4)
            {
                for (auto building : buildings)
                {
                    if (building.Type == BUILDING_CENTER)
                    {
                        auto dest = bfsSearchBuilding(building, getBuildingSize(BUILDING_HOME), 1);
                        if (dest.first != -1 && dest.second != -1)
                        {
                            HumanBuild(farmer.SN, BUILDING_HOME, dest.first, dest.second);
                        }
                    }
                }
            }
            else if (buildings.size() < 5)
            {
                auto dest = bfsDockSearch(farmer);
                if (dest.first.first != -1) // 确保找到了有效位置
                {
                    HumanBuild(farmer.SN, BUILDING_DOCK, dest.first.first, dest.first.second);
                }
            }
            else if (buildings.size() < 6)
            {
                auto food = bfsSearch(farmer, 7);
                auto deer = resourceTable[food.second];
                auto dest = bfsSearchBuilding(deer, getBuildingSize(BUILDING_STOCK), 1);
                if (dest.first != -1 && dest.second != -1 && info.Wood >= BUILD_STOCK_WOOD)
                {
                    HumanBuild(farmer.SN, BUILDING_STOCK, dest.first, dest.second);
                }
            }
            else if (buildings.size() < 8)
            {
                for (auto &building : buildings)
                {
                    if (building.Type == BUILDING_CENTER)
                    {
                        auto dest = bfsSearchBuilding(building, getBuildingSize(BUILDING_HOME), 1);
                        if (dest.first != -1 && dest.second != -1 && info.Wood >= BUILD_HOUSE_WOOD)
                        {
                            HumanBuild(farmer.SN, BUILDING_HOME, dest.first, dest.second);
                        }
                    }
                }
            }
            else
            {
                farmerRoles[farmer.SN] = "woodcutter";
            }
        }
        else if (role == "woodcutter")
        {
            auto dest = bfsSearch(farmer, 5); // 找树
            HumanMove(farmer.SN, dest.first.first * BLOCKSIDELENGTH, dest.first.second * BLOCKSIDELENGTH);
            HumanAction(farmer.SN, dest.second);
        }
        else if (role == "hunter")
        {
            auto dest = bfsSearch(farmer, 7); // 找猎物
            HumanMove(farmer.SN, dest.first.first * BLOCKSIDELENGTH, dest.first.second * BLOCKSIDELENGTH);
            HumanAction(farmer.SN, dest.second);
        }
    }
}

// 第一阶段建筑建造逻辑
void UsrAI::buildLogic01()
{
    auto farmers = info.farmers;
    auto buildings = info.buildings;
    if (farmers.size() < 10 && info.Meat >= 50)
    {
        for (auto &building : buildings)
        {
            if (building.Type == BUILDING_CENTER)
            {
                BuildingAction(building.SN, BUILDING_CENTER_CREATEFARMER);
            }
        }
    }
    for (auto &building : buildings)
    {
        int count = 0;
        for (auto &farmer : farmers)
        {
            if (farmer.FarmerSort == 2)
            {
                count++;
            }
        }
        if (building.Type == BUILDING_DOCK && info.Wood >= BUILDING_DOCK_CREATE_SAILING_WOOD)
        {
            if (count >= 4)
            {
                break;
            }
            BuildingAction(building.SN, BUILDING_DOCK_CREATE_SAILING);
        }
    }
    for (auto &boat : sailingFarmers)
    {
        if (boat.NowState == HUMAN_STATE_IDLE)
        {
            auto path = sailingBfsSearch(boat, 8);
            if (!path.empty())
            {
                int tx = path.back().first;
                int ty = path.back().second;
                if (mapinfo[tx][ty].type == 8)
                {
                    HumanAction(boat.SN, mapinfo[tx][ty].SN);
                }
                else
                {
                    for (int i = 1; i < path.size(); ++i)
                    {
                        int x = path[i].first;
                        int y = path[i].second;
                        if (x < 3 || x >= 125 || y < 3 || y >= 125 || isEnemyCoast[x][y] == 2)
                        {
                            for (auto &building : buildings)
                            {
                                if (building.Type == BUILDING_DOCK)
                                {
                                    HumanMove(boat.SN, building.BlockDR * BLOCKSIDELENGTH, building.BlockUR * BLOCKSIDELENGTH);
                                }
                            }
                            break;
                        }
                        if (mapinfo[x][y].visible && mapinfo[x][y].type == 1)
                        {
                            HumanMove(boat.SN, x * BLOCKSIDELENGTH, y * BLOCKSIDELENGTH);
                        }
                    }
                }
            }
        }
    }
}

// 第二阶段农民角色分配
void UsrAI::assignFarmerRoles02()
{
    for (auto &farmer : idleFarmers)
    {
        if (farmerRoles.find(farmer.SN) == farmerRoles.end())
        {
            if (countRole("builder") < 1)
            {
                farmerRoles[farmer.SN] = "builder";
            }
            else
            {
                farmerRoles[farmer.SN] = "woodcutter";
            }
        }
    }
}

// 第二阶段农民行为
void UsrAI::farmerDoWork02()
{
    auto buildings = info.buildings;
    for (auto &farmer : huntingFarmers)
    {
        farmer.NowState = HUMAN_STATE_IDLE;
        farmerRoles[farmer.SN] = "woodcutter";
    }
    for (auto &farmer : idleFarmers)
    {
        string role = farmerRoles[farmer.SN];
        if (role == "builder")
        {
            if (buildings.size() < 11)
            {
                for (auto &building : buildings)
                {
                    if (building.Type == BUILDING_CENTER)
                    {
                        auto dest = bfsSearchBuilding(building, getBuildingSize(BUILDING_HOME), 1);
                        if (dest.first != -1 && dest.second != -1 && info.Wood >= BUILD_HOUSE_WOOD)
                        {
                            HumanBuild(farmer.SN, BUILDING_HOME, dest.first, dest.second);
                        }
                    }
                }
            }
            else if (buildings.size() < 12)
            {
                for (auto &building : buildings)
                {
                    if (building.Type == BUILDING_CENTER)
                    {
                        auto dest = bfsSearchBuilding(building, getBuildingSize(BUILDING_GRANARY), 1);
                        if (dest.first != -1 && dest.second != -1 && info.Wood >= BUILD_GRANARY_WOOD)
                        {
                            HumanBuild(farmer.SN, BUILDING_GRANARY, dest.first, dest.second);
                        }
                    }
                }
            }
            else if (buildings.size() < 13)
            {
                for (auto &building : buildings)
                {
                    if (building.Type == BUILDING_CENTER)
                    {
                        auto dest = bfsSearchBuilding(building, getBuildingSize(BUILDING_MARKET), 1);
                        if (dest.first != -1 && dest.second != -1 && info.Wood >= BUILD_MARKET_WOOD)
                        {
                            HumanBuild(farmer.SN, BUILDING_MARKET, dest.first, dest.second);
                        }
                    }
                }
            }
            else
            {
                for (auto building : buildings)
                {
                    if (building.Type == BUILDING_CENTER)
                    {
                        auto dest = bfsSearchBuilding(building, getBuildingSize(BUILDING_FARM), 1);
                        if (dest.first != -1 && dest.second != -1 && info.Wood >= BUILD_FARM_WOOD)
                        {
                            HumanBuild(farmer.SN, BUILDING_FARM, dest.first, dest.second);
                        }
                    }
                }
            }
        }
        else if (role == "stonecutter")
        {
            auto dest = bfsSearch(farmer, 6);
            if (dest.first.first != -1 && dest.first.second != -1)
            {
                HumanMove(farmer.SN, dest.first.first * BLOCKSIDELENGTH, dest.first.second * BLOCKSIDELENGTH);
                HumanAction(farmer.SN, dest.second);
            }
        }
        else if (role == "hunter")
        {
            auto dest = bfsSearch(farmer, 7);
            if (dest.first.first != -1 && dest.first.second != -1)
            {
                HumanMove(farmer.SN, dest.first.first * BLOCKSIDELENGTH, dest.first.second * BLOCKSIDELENGTH);
                HumanAction(farmer.SN, dest.second);
            }
        }
        else if (role == "woodcutter")
        {
            auto dest = bfsSearch(farmer, 5);
            if (dest.first.first != -1 && dest.first.second != -1)
            {
                HumanMove(farmer.SN, dest.first.first * BLOCKSIDELENGTH, dest.first.second * BLOCKSIDELENGTH);
                HumanAction(farmer.SN, dest.second);
            }
        }
    }
    // 到达对岸时，直接销毁2艘渔船，销毁渔船只保留5艘
}

// 第二阶段建造逻辑
int myDestCnt = 0;
bool success = false;
void UsrAI::buildLogic02()
{
    auto farmers = info.farmers;
    auto buildings = info.buildings;
    auto armies = info.armies;
    if (farmers.size() < 20 && info.Meat >= 50)
    {
        for (auto &building : buildings)
        {
            if (building.Type == BUILDING_CENTER)
            {
                BuildingAction(building.SN, BUILDING_CENTER_CREATEFARMER);
            }
        }
    }
    if (at_ships.size() < 8 && info.Wood >= BUILDING_DOCK_CREATE_SHIP_WOOD && at_ship_count.size() < 10)
    {
        for (auto &building : buildings)
        {
            if (building.Type == BUILDING_DOCK)
            {
                BuildingAction(building.SN, BUILDING_DOCK_CREATE_SHIP);
                break;
            }
        }
    }
    if (at_ship_count.size() >= 8 && info.Wood >= BUILDING_DOCK_CREATE_WOOD_BOAT_WOOD &&
            transportFarmers.size() < 1)
    {
        for(auto& building : buildings){
            if(building.Type == BUILDING_DOCK)
            {
                BuildingAction(building.SN, BUILDING_DOCK_CREATE_WOOD_BOAT);
                break;
            }
        }
    }
    for (auto &boat : sailingFarmers)
    {
        if (boat.NowState == HUMAN_STATE_IDLE)
        {
            auto path = sailingBfsSearch(boat, 8);
            if (!path.empty())
            {
                int tx = path.back().first;
                int ty = path.back().second;
                if (mapinfo[tx][ty].type == 8)
                {
                    HumanAction(boat.SN, mapinfo[tx][ty].SN);
                }
                else
                {
                    for (int i = 0; i < path.size(); i++)
                    {
                        int x = path[i].first;
                        int y = path[i].second;
                        if (mapinfo[x][y].visible && mapinfo[x][y].type == 1)
                        {
                            HumanMove(boat.SN, x * BLOCKSIDELENGTH, y * BLOCKSIDELENGTH);
                        }
                    }
                }
            }
        }
    }

    for(auto& boat : transportFarmers){
        if(boat.NowState == HUMAN_STATE_IDLE){
            int gameframe = info.GameFrame;
            double mycoast_x = 0, mycoast_y = 0;
            int x = 0, y = 0;
            auto mydest = bfsSearchMyCoast(boat);
            if(success == false && mydest.first != -1){
                for(int i = 0; i < 4; i ++){
                    int nx = mydest.first + dir[i][0], ny = mydest.second + dir[i][1];
                    if(isMyCoast[nx][ny] == 1){
                        mycoast_x = mydest.first * 0.33 + nx * 0.67, mycoast_y = mydest.first * 0.33 + ny * 0.67;
                        break;
                    }
                }
                DebugText("我方坐标为 ： " + std::to_string(mycoast_x * BLOCKSIDELENGTH) + " " + std::to_string(mycoast_y * BLOCKSIDELENGTH));
                HumanMove(boat.SN, mycoast_x * BLOCKSIDELENGTH, mycoast_y * BLOCKSIDELENGTH);

                for(auto& farmer : cuttingFarmers){
                    if(farmerRoles[farmer.SN] != "board" && countRole("board") < 5){
                        HumanMove(farmer.SN, mydest.first * BLOCKSIDELENGTH, mydest.second * BLOCKSIDELENGTH);
                        HumanAction(farmer.SN, boat.SN);
                        farmerRoles[farmer.SN] = "board";
                    }
                }
                success = true;
            }

            int boat_dir[8][2] = {
                {1, 0}, {0, 1}, {0, -1}, {-1, 0}, {1, 1}, {1, -1}, {-1, 1}, {-1, -1}
            };
            double enemycoast_x = 0, enemycoast_y = 0;
            if(boat.Resource == 5 && myDestCnt == 0){
                for(int i = 1; i < detectPath.size(); i ++){
                    x = detectPath[i].first, y = detectPath[i].second;

                    if(isEnemyCoast[x][y] == 2){
                        for(int i = 0; i < 8; i ++){
                            int nx = x + boat_dir[i][0], ny = y + boat_dir[i][1];
                            if(isEnemyCoast[nx][ny] == 1){
                                enemycoast_x = x * 0.48 + nx * 0.52, enemycoast_y = y * 0.48 + ny * 0.52;
                            }
                        }
//                        enemycoast_x = x, enemycoast_y = y;
                        break;
                    }
                }
                DebugText("敌方坐标为 ： " + std::to_string(enemycoast_x * BLOCKSIDELENGTH) + " " + std::to_string(enemycoast_y * BLOCKSIDELENGTH));
                HumanMove(boat.SN, enemycoast_x * BLOCKSIDELENGTH, enemycoast_y * BLOCKSIDELENGTH);
                myDestCnt ++;
            }
        }
    }
}
// 第三阶段
void UsrAI::assignFarmerRoles03(){

}
void UsrAI::farmerDoWork03(){

}
void UsrAI::buildLogic03(){

}
void UsrAI::boatFishingLogic()
{
    auto buildings = info.buildings;
    for (auto &boat : sailingFarmers)
    {
        if (boat.NowState == HUMAN_STATE_IDLE)
        {
            auto path = sailingBfsSearch(boat, 8);
            if (!path.empty())
            {
                int tx = path.back().first;
                int ty = path.back().second;
                if (mapinfo[tx][ty].type == 8)
                {
                    HumanAction(boat.SN, mapinfo[tx][ty].SN);
                }
                else
                {
                    for (int i = 1; i < path.size(); ++i)
                    {
                        int x = path[i].first;
                        int y = path[i].second;
                        if (mapinfo[x][y].visible && mapinfo[x][y].type == 1)
                        {
                            HumanMove(boat.SN, x * BLOCKSIDELENGTH, y * BLOCKSIDELENGTH);
                        }
                    }
                }
            }
        }
    }
}
// 战船侦查逻辑
int detectShipSN = -1; // 只记录一艘侦察船
void UsrAI::warshipDetectLogic()
{
    info = getInfo();

    // 只在没有侦察船的情况下分配一艘
    if (detectShipSN == -1 && !at_ships.empty())
    {
        detectShipSN = at_ships[0].SN;
        shipRole[detectShipSN] = "detect";
    }
    // 其余新船分配为wait
    for (auto &at_ship : at_ships)
    {
        at_ship_count.insert(at_ship.SN);
//        UsrAI::allShipNum.push_back(at_ship.SN);
        if (shipRole.find(at_ship.SN) == shipRole.end())
        {
            shipRole[at_ship.SN] = "wait";
        }
    }

    // 侦察船执行侦察并保存路径
    for (auto &at_ship : at_ships)
    {
        if (at_ship.SN == detectShipSN && shipRole[at_ship.SN] == "detect")
        {
            auto dest = guessEnemyLoc();
            auto path = bfsSearchEnemyLand(at_ship, dest);
            if (!path.empty())
            {
                detectPath = path;
                for (int i = 1; i < path.size() && info.GameFrame % 50 == 0; i++)
                {
                    int x = path[i].first, y = path[i].second;
                    HumanMove(at_ship.SN, x * BLOCKSIDELENGTH, y * BLOCKSIDELENGTH);
                }
            }
        }
    }
}

// 战船集结攻击逻辑
void UsrAI::warshipAttackLogic()
{
    // 如果战船数量达到7艘或以上，所有wait状态的战船开始攻击
    if (at_ship_count.size() >= 8)
    {

        for (auto &at_ship : at_ships)
        {
            // 只让"wait"状态的船出发攻击，"detect"船继续侦查
            if (shipRole[at_ship.SN] == "wait")
            {
                shipRole[at_ship.SN] = "attack";

                // 从保存的侦察路径中获取目标位置
                for (int i = 0; i < detectPath.size(); i++)
                {
                    int x = detectPath[i].first, y = detectPath[i].second;
                    HumanMove(at_ship.SN, x * BLOCKSIDELENGTH, y * BLOCKSIDELENGTH);
                }
            }
        }
    }
    else
    {
        int waitCount = 0;
        for (auto &at_ship : at_ships)
        {
            if (shipRole[at_ship.SN] == "wait")
            {
                waitCount++;
            }
        }
    }
}
// 第一阶段测试主流程
void UsrAI::stage_01_test()
{
    info = getInfo();
    getFarmerState();
    assignFarmerRoles01();
    farmerDoWork01();
    buildLogic01();
    // 战船侦查和集结
    warshipDetectLogic();
    warshipAttackLogic();
    // 其余升级等逻辑
    if (info.Meat >= BUILDING_CENTER_UPGRADE_FOOD)
    {
        for (auto &building : info.buildings)
        {
            if (building.Type == BUILDING_CENTER)
            {
                BuildingAction(building.SN, BUILDING_CENTER_UPGRADE);
            }
        }
    }
    if (info.civilizationStage == 2)
    {
        for (auto &building : info.buildings)
        {
            if (building.Type == BUILDING_CENTER && info.Meat >= BUILDING_CENTER_CREATEFARMER_FOOD && info.farmers.size() < 14)
            {
                BuildingAction(building.SN, BUILDING_CENTER_CREATEFARMER);
            }
            if (building.Type == BUILDING_DOCK && info.Wood >= BUILDING_DOCK_CREATE_SHIP_WOOD)
            {
                BuildingAction(building.SN, BUILDING_DOCK_CREATE_SHIP);
            }
        }
    }
}

// 第二阶段测试主流程
void UsrAI::stage_02_test()
{
    info = getInfo();
    getFarmerState();
    assignFarmerRoles02();
    farmerDoWork02();
    buildLogic02();
    buildDefensiveTowers(); // 新增：建造防御塔
    manageGroundForces(); // 新增：管理地面单位
    // 战船侦查和集结
    warshipDetectLogic();
    warshipAttackLogic();
    // boatTransport(); // 函数未实现
}

void UsrAI::processData()
{
    info = getInfo();

    getMapInfo();

    getShipVisit();

    getObjectTable();

    getFarmerState();

    updateShipStatus();

    if (info.GameFrame == 100)
    {
        checkMyLand();
        getMyCoast();
    }
    if (stage == 2)
    {
        checkEnemyLand();
        getEnemyCoast();
    }

    checkStage();
    if (stage == 1)
    {
        stage_01_test();
    }
    else if (stage == 2)
    {
        stage_02_test();
    }

    getDebugTexts();

    autoAttackEnemy();

    findFish();

    return;
}

// 新增：自动建造防御塔
void UsrAI::buildDefensiveTowers()
{
    info = getInfo();
    auto buildings = info.buildings;
    tagBuilding* center = nullptr;
    int towerCount = 0;

    for (auto& building : buildings)
    {
        if (building.Type == BUILDING_CENTER)
        {
            center = &building;
        }
        if (building.Type == BUILDING_ARROWTOWER)
        {
            towerCount++;
        }
    }

    // 如果箭塔数量少于2座，并且有足够的资源，则建造箭塔
    if (center != nullptr && towerCount < 2  && info.Stone >= BUILD_ARROWTOWER_STONE)
    {
        for (auto& farmer : idleFarmers)
        {
            if (farmerRoles.count(farmer.SN) && farmerRoles[farmer.SN] == "builder")
            {
                // 在城镇中心附近寻找一个位置建造箭塔
                auto dest = bfsSearchBuilding(*center, getBuildingSize(BUILDING_ARROWTOWER), 1);
                if (dest.first != -1 && dest.second != -1)
                {
                    HumanBuild(farmer.SN, BUILDING_ARROWTOWER, dest.first, dest.second);
                    DebugText("命令农民 " + std::to_string(farmer.SN) + " 建造箭塔");
                    break; // 只派一个农民去建造
                }
            }
        }
    }
}

// 新增：管理地面单位和军营
void UsrAI::manageGroundForces()
{
    info = getInfo();
    auto buildings = info.buildings;
    tagBuilding* center = nullptr;
    tagBuilding* armyCamp = nullptr;
    bool hasArmyCamp = false;

    for (auto& building : buildings)
    {
        if (building.Type == BUILDING_CENTER)
        {
            center = &building;
        }
        if (building.Type == BUILDING_ARMYCAMP)
        {
            hasArmyCamp = true;
            if(building.Percent == 100)
            {
                armyCamp = &building;
            }
        }
    }

    // 1. 如果没有军营，就派人建造一个
    if (center != nullptr && !hasArmyCamp && info.Wood >= BUILD_ARMYCAMP_WOOD)
    {
        for (auto& farmer : idleFarmers)
        {
            if (farmerRoles.count(farmer.SN) && farmerRoles[farmer.SN] == "builder")
            {
                auto dest = bfsSearchBuilding(*center, getBuildingSize(BUILDING_ARMYCAMP), 1);
                if (dest.first != -1 && dest.second != -1)
                {
                    HumanBuild(farmer.SN, BUILDING_ARMYCAMP, dest.first, dest.second);
                    DebugText("命令农民 " + std::to_string(farmer.SN) + " 建造军营");
                    return; // 派一个农民去建就行
                }
            }
        }
    }

    // 2. 如果军营已建成，并且资源足够，就生产棍棒兵
    if (armyCamp != nullptr)
    {
        // 限制地面单位数量，避免过多消耗资源
        int groundArmyCount = 0;
        for(auto& army : info.armies){
            if(army.Sort == AT_CLUBMAN || army.Sort == AT_SLINGER || army.Sort == AT_SWORDSMAN || army.Sort == AT_BOWMAN){
                groundArmyCount++;
            }
        }

        if(groundArmyCount < 10) // 示例：最多生产10个地面单位
        {
             BuildingAction(armyCamp->SN, BUILDING_ARMYCAMP_CREATE_CLUBMAN);
             DebugText("军营 " + std::to_string(armyCamp->SN) + " 正在生产棍棒兵");
        }
    }
}
